﻿using System;
using System.Collections.Generic;

using Microsoft.Xna.Framework;
using Microsoft.Xna.Framework.Graphics;

using ZoeEngine.Framework;
using ZoeEngine.Framework.Rendering;

namespace ZoeEngine.Services.Scene
{
    public class SceneProvider : DrawableGameComponent, ISceneService
    {
        private ComponentManager _manager;

        private SpriteBatch _spriteBatch;
        private ICamera _sceneCamera;

        private SpriteFont font;

        public SceneProvider(Game game)
            : base(game)
        {
            if (game.Services.GetService(typeof(ISceneService)) != null)
            {
                throw new ArgumentException("A scene provider already exists.");
            }
            game.Services.AddService(typeof(ISceneService), this);
            _manager = new ComponentManager();
            _sceneCamera = new Camera(Game);
        }

        protected override void LoadContent()
        {
            _manager.LoadContent();
            base.LoadContent();
        }
        public override void Initialize()
        {
            base.Initialize();
            _manager.Initialize();
            _spriteBatch = new SpriteBatch(GraphicsDevice);
        }
        public override void Update(GameTime gameTime)
        {
            _manager.Update(gameTime);
            base.Update(gameTime);
        }
        public override void Draw(GameTime gameTime)
        {
            GraphicsDevice.Clear(Color.PowderBlue);

            _spriteBatch.Begin(SpriteSortMode.Deferred, BlendState.AlphaBlend, null, null, null, null, _sceneCamera.View);
            _manager.Draw(gameTime, _spriteBatch);
            _spriteBatch.End();

            base.Draw(gameTime);
        }
        protected override void UnloadContent()
        {
            _manager.UnloadContent();
            base.UnloadContent();
        }
        protected override void Dispose(bool disposing)
        {
            if (disposing)
            {
                if (this.Game.Services.GetService(typeof(ISceneService)) == this)
                {
                    this.Game.Services.RemoveService(typeof(ISceneService));
                }
            }
            base.Dispose(disposing);
        }

        public ComponentManager Manager
        {
            get
            {
                return _manager;
            }
        }
        public ICamera SceneCamera
        {
            get
            {
                return _sceneCamera;
            }
        }
    }
}
